﻿#include "Config.h"
#include "NetworkClient.h"
#include "MsgHandler/MsgTypes.h"
#include "MsgHandler/MsgPool.h"
#include <event2/buffer.h>

namespace Network {

NetworkClient::NetworkClient( int fd, TcpSlaveServer * s, int id ):
	TcpConduit(fd, s, id), m_RemoteIP( 0 ), m_RemotePort( 0 )
{
	struct sockaddr_in peerAddr;
	getAddr(&peerAddr);
	m_RemoteIP = ntohl(peerAddr.sin_addr.s_addr);
	m_RemotePort = ntohs(peerAddr.sin_port);
}

UInt16 NetworkClient::parsePacket( struct evbuffer * buf, int &off, int &len )
{
	size_t l = evbuffer_get_length(buf);
	if(l < 6)
	{
		off = 0;
		len = 0;
		return 0;
	}
	UInt8 * buf_ = static_cast<UInt8 *>(evbuffer_pullup(buf, 6));
	UInt16 len2 = *reinterpret_cast<UInt16 *>(buf_);
	if(len2 > l)
	{
		off = 0;
		len = 0;
		return 0;
	}

	off = 6;
	len = len2;

	return *reinterpret_cast<UInt16 *>(&buf_[4]);
}

void NetworkClient::onRecv( UInt16 cmd, int len, void * buf )
{

}

void NetworkClient::onAccepted()
{
	struct sockaddr_in peerAddr;
	getAddr(&peerAddr);
	m_RemoteIP = ntohl(peerAddr.sin_addr.s_addr);
	m_RemotePort = ntohs(peerAddr.sin_port);
}

void NetworkClient::onDisconnected()
{

}

void NetworkClient::SetClientAddr( const struct sockaddr * addr )
{
	const struct sockaddr_in * peerAddr = reinterpret_cast<const struct sockaddr_in *>(addr);
	m_RemoteIP = ntohl(peerAddr->sin_addr.s_addr);
	m_RemotePort = ntohs(peerAddr->sin_port);
}

}